
#include <algorithm>
#include <cmath>
#include "filterwipe.h"
#include "text.h"

namespace Wishmaster
{
	FilterWipe::FilterWipe(const QString& name) : Filter(name)
	{
	}

	FilterWipe::~FilterWipe()
	{
	}

	bool FilterWipe::check(PostPtr post)
	{
		QString text = post->text();
		text = htmlToPlainText(text);
		if(checkText(text))
			return true;
		if(checkText(post->topic())) // Topic should be already in plain text
			return true;
		return false;
	}

	bool FilterWipe::checkText(const QString& text)
	{
		if(text.isEmpty())
			return false;
		QString t = text;
		t.replace(QRegExp("\\W+"), " ");
		QStringList l = t.split(' ', QString::SkipEmptyParts);
		if(l.size() < 8)
			return false;

		QMap<QString, uint> words;
		QSet<QString> repeated;
		foreach(QString word, l)
		{
			if(words[word]++ >= 3 * (std::max(text.size(), 80) / 400.))
				repeated.insert(word);
		}
		if(repeated.size() > words.size() * 0.40)
			return true;

		if(checkCapitals(text))
			return true;
		return false;
	}

	bool FilterWipe::checkCapitals(const QString& text)
	{
		int upper = 0;
		for(int i = 0; i < text.size(); i++)
		{
			if(text.at(i).isUpper())
				upper++;
		}
		if((double)upper / text.size() > 0.5)
			return true;
		return false;
	}

	QString FilterWipe::id()
	{
		return "filterwipe";
	}

	QString FilterWipe::serialize()
	{
		return "";
	}

	bool FilterWipe::deserialize(const QString& s)
	{
		return true;
	}
	
	QSharedPointer<Filter> FilterWipe::clone(const QString& name)
	{
		return FilterPtr();
	}
}

